package cn.itcast.bos.service.system.Impl;

import cn.itcast.bos.Dao.system.MenuRepository;
import cn.itcast.bos.Dao.system.PermissionRepository;
import cn.itcast.bos.Dao.system.RoleRespostiory;
import cn.itcast.bos.domain.system.Menu;
import cn.itcast.bos.domain.system.Permission;
import cn.itcast.bos.domain.system.Role;
import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {
    @Autowired
    private PermissionRepository permissionRepository;
    @Autowired
    private MenuRepository menuRepository;
    @Autowired
    private RoleRespostiory roleRespostiory;
    @Override
    public List<Role> findByUser(User user) {
        if(user.getUsername().equals("smbe")){
            //查询所有角色
            return roleRespostiory.findAll();
        }else {
            Integer id = user.getId();
            return roleRespostiory.finByUser(id);
        }


    }

    @Override
    public List<Role> findAll() {
        return roleRespostiory.findAll();
    }

    @Override
    public void save(Role role, String[] permissionIds, String menuIds) {
        //保存role
        roleRespostiory.save(role);
        //关联保存权限
        if(permissionIds.length !=0 && permissionIds !=null){
            for (String id:permissionIds ){
                Permission permission = permissionRepository.findOne(Integer.parseInt(id));
                role.getPermissions().add(permission);
            }
        }
        //关联保存菜单
        if(menuIds !=null){
            for(String id:menuIds.split(",")){
                Menu menu = menuRepository.findOne(Integer.parseInt(id));
                role.getMenus().add(menu);
            }
        }
    }

}
